
using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Diagrams;
using DslFactory.Utilities.DteCodeModel;
using System.Collections.Generic;

namespace Dslfactory.wcfLanguage
{
 public partial class wcfLanguageDomainModel
 {
  /// <summary>
  /// Rule changing an Interface into a ServiceContract and vice-versa
  /// for interfaces into the project, and IsInterfaceContact is changed
  /// </summary>
  [RuleOn(typeof(Method), InitiallyDisabled=true)]
  public class MethodPropertiesCoherence : ChangeRule
  {
   public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
   {
    KnownCodeTypes knownCodeTypes = KnownCodeTypes.FromStore(e.ModelElement.Store);
    Method method = e.ModelElement as Method;

    if (method.IsDeleting || method.IsDeleted)
     return;

    // Label
    if (e.DomainProperty.Id == Method.LabelDomainPropertyId)
    {
     string name;
     string returnType;
     List<KeyValuePair<string, string>> parameters;

     MethodLabel.ParseLabel(knownCodeTypes, method.Label, out name, out returnType, out parameters);
     method.Signature = MethodLabel.ComputeSignature(name, returnType, parameters);
     method.Name = name;
     method.Prototype = MethodLabel.ComputePrototype(name, returnType, parameters);
    }

    // Name
    else if (e.DomainProperty.Id == Method.NameDomainPropertyId)
    {
     string name;
     string returnType;
     List<KeyValuePair<string, string>> parameters;

     MethodLabel.ParseLabel(knownCodeTypes, method.Label, out name, out returnType, out parameters);
     method.Label = MethodLabel.ComputeLabel(knownCodeTypes, method.Name, returnType, parameters);
    }

    // Prototype
    else if (e.DomainProperty.Id == Method.PrototypeDomainPropertyId)
    {
     string name;
     string returnType;
     List<KeyValuePair<string, string>> parameters;

     MethodLabel.ParsePrototype(method.Prototype, out name, out returnType, out parameters);
//     method.Signature = MethodLabel.ComputeSignature(name, returnType, parameters);
//     method.Name = name;
     method.Label = MethodLabel.ComputeLabel(knownCodeTypes, name, returnType, parameters);
    }

    // Sets the interface as an 
    else if (e.DomainProperty.Id == Method.IsOperationContractDomainPropertyId)
    {
     if (method.IsOperationContract && (method.Interface!=null))
      if (!method.Interface.IsServiceContract)
       method.Interface.IsServiceContract = true;
     // Do not do anything else after this operation (the Interface has changed : do not keep a reference on it)
    }
   }
  }
 }
}
